"""
用户管理相关的 API 端点
"""
from typing import List
from fastapi import APIRouter, Depends, HTTPException, status as status_module, Query
from ....schemas.user import UserResponse, UserCreate, UserUpdate, LoginRequest, UserListResponse
from ....schemas.response import BaseResponse
from ....crud.user import user_crud
from ....models.user import User, UserStatus
from ...deps import get_current_active_user, require_admin

router = APIRouter()


@router.get(
    "/",
    response_model=BaseResponse[UserListResponse],
    summary="获取用户列表",
    description="获取所有用户列表（需要管理员权限）"
)
async def get_users(
    skip: int = Query(0, ge=0, description="跳过的记录数"),
    limit: int = Query(100, ge=1, le=100, description="返回的记录数"),
    current_user: User = Depends(require_admin)
):
    """获取用户列表"""
    users = await user_crud.get_users(skip=skip, limit=limit)
    total = await user_crud.get_users_count()
    user_list = [UserResponse.model_validate(user) for user in users]
    return BaseResponse[UserListResponse](
        code=200,
        message="获取用户列表成功",
        data=UserListResponse(total=total, users=user_list)
    )


@router.get(
    "/me",
    response_model=BaseResponse[UserResponse],
    summary="获取当前用户信息",
    description="获取当前登录用户的详细信息"
)
async def get_current_user_info(
    current_user: User = Depends(get_current_active_user)
):
    """获取当前用户信息"""
    return BaseResponse[UserResponse](
        code=200,
        message="获取用户信息成功",
        data=UserResponse.model_validate(current_user)
    )


@router.get(
    "/{job_number}",
    response_model=BaseResponse[UserResponse],
    summary="根据工号获取用户",
    description="根据用户工号获取用户详细信息（需要管理员权限）"
)
async def get_user_by_job_number(
    job_number: str,
    current_user: User = Depends(require_admin)
):
    """根据job_number获取用户"""
    user = await user_crud.get_user_by_id(job_number)
    return BaseResponse[UserResponse](
        code=200,
        message="获取用户信息成功",
        data=UserResponse.model_validate(user)
    )


@router.post(
    "/",
    response_model=BaseResponse[UserResponse],
    summary="创建新用户",
    description="创建新用户（需要管理员权限）"
)
async def create_user(
    user_data: UserCreate,
    current_user: User = Depends(require_admin)
):

    """创建新用户"""
    user = await user_crud.create_user(user_data)
    return BaseResponse[UserResponse](
        code=200,
        message="创建用户成功",
        data=UserResponse.model_validate(user)
    )


@router.put(
    "/status/{job_number}",
    response_model=BaseResponse[UserResponse],
    summary="更新用户状态",
    description="更新指定用户的状态（需要管理员权限）"
)
async def update_user_status(
    job_number: str,
    status: str,
    current_user: User = Depends(require_admin)
):
    """更新用户状态"""
    # 将字符串转换为UserStatus枚举
    if status == "1":
        user_status = UserStatus.ACTIVE
    elif status == "0":
        user_status = UserStatus.INACTIVE
    else:
        raise HTTPException(
            status_code=status_module.HTTP_400_BAD_REQUEST,
            detail="无效的状态值，只支持 '1'（激活）或 '0'（禁用）"
        )
    
    user = await user_crud.change_user_status(job_number, user_status)
    return BaseResponse[UserResponse](
        code=200,
        message="更新用户状态成功",
        data=UserResponse.model_validate(user)
    )


@router.put(
    "/{job_number}",
    response_model=BaseResponse[UserResponse],
    summary="更新用户信息",
    description="更新指定用户的信息（需要管理员权限）"
)
async def update_user(
    job_number: str,
    user_data: UserUpdate,
    current_user: User = Depends(require_admin)
):
    """更新用户信息"""
    user = await user_crud.update_user(job_number, user_data)
    return BaseResponse[UserResponse](
        code=200,
        message="更新用户成功",
        data=UserResponse.model_validate(user)
    )


@router.delete(
    "/{job_number}",
    response_model=BaseResponse[str],
    summary="删除用户",
    description="删除指定的用户（需要管理员权限）"
)
async def delete_user(
    job_number: str,
    current_user: User = Depends(require_admin)
):
    """删除用户"""
    await user_crud.delete_user(job_number)
    print(f"用户 {job_number} 已被成功删除")
    return BaseResponse[str](
        code=200,
        message="删除用户成功",
        data="用户已被成功删除"
    )


@router.post(
    "/admin_pwd",
    response_model=BaseResponse[str],
    summary="管理员更新用户密码",
    description="更新指定用户的密码（需要管理员权限）"
)
async def update_user_password_admin(
    admin_update_pwd: LoginRequest,
    current_user: User = Depends(require_admin)
):
    """管理员更新用户密码"""
    await user_crud.update_user_password_admin(
        admin_update_pwd.job_number, admin_update_pwd.password)
    return BaseResponse[str](
        code=200,
        message="更新用户密码成功",
        data="用户密码已被成功更新"
    )

